<?php

namespace App\Store\Controllers\Member;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\Member;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\Account;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsPricetype;
use App\Store\Models\Member\SiteMemberLv;
use App\Store\Models\Order\OrderSalesGoods;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use App\Store\Services\Member\CommonMember;
use Illuminate\Support\Facades\DB;
use Vtiful\Kernel\Format;

/**
 * 会员消费记录
 */
class SiteMemberConsumeRecord extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = \App\Store\Models\Member\SiteMemberConsumeRecord::getlist($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /***
     *   导入系统使用者自定义消费记录数据
     *
     */
    public function doimport(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $filepathname = $request->filepathname;
        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $config = ['path' => storage_path()];
            $excel = new \Vtiful\Kernel\Excel($config);
            $data = $excel->openFile($filepathname)
                ->openSheet()
                ->setType([
                    5 => \Vtiful\Kernel\Excel::TYPE_TIMESTAMP,
                ])
                ->getSheetData();
            //dd($data);
            $insertData = [];
            $rowKey = [
                'mem_name:s', 'mem_card_no:s', 'mobile:s', 'order_sn:s', 'store_name:s', 'order_at:int', 'order_store:s','shopping_account:s',
                'goods_name:s', 'goods_sn_code:s', 'goods_category:s', 'cert_no:s', 'goods_price:int', 'price:int', 'order_discount:decimal:2',
                'receive_money:int', 'recovery_money:int', 'points:int', 'piece_weight:decimal:3', 'glod_weight:decimal:3', 'sale_price:int', 'fee:int',
                'real_money:int', 'goods_pricetype:s', 'count:int', 'discount_money:int', 'cost_price:int', 'tag_price:int', 'material_price:int', 'is_replace:int', 'remark:s',
            ];
            //dd(count($data));
            if (count($data) > 10001) {
                return response()->json(['code' => '001', 'msg' => '超过导入数据上限，最多导入10000条', 'data' => []]);
            }
            $keyAmount = ['goods_price', 'price', 'receive_money', 'recovery_money', 'sale_price', 'fee', 'real_money', 'tag_price', 'material_price', 'cost_price', 'discount_money'];
            foreach ($data as $key => $item) {
                if ($key === 0) continue;
                if ($key > 10000) break;

                $row = [];
                for ($i = 0; $i < count($item); $i++) {
                    $require = explode(':', $rowKey[$i]);
                    $data_key = $require[0];
                    if (!empty($item[$i])) {
                        //时间戳转化
                        if ($require[0] == 'order_at') {
                            $row[$data_key] = (!empty($item[$i])&&is_numeric($item[$i]))?$item[$i]:strtotime($item[$i]);
                            //dd($item[$i]);
                        } else if ($require[0] == 'is_replace') {
                            $row[$data_key] = $item[$i] == '是' ? 2 : 1;
                        } else {
                            if (in_array($require[0], $keyAmount)) {
                                $row[$data_key] = bcmul($item[$i], 100);
                            } else {
                                $row[$data_key] = $item[$i];
                            }
                        }
                    } else {
                        //如果导入单元格为空，需要处理，为了统一插入
                        if ($require[1] == 's') {
                            $row[$data_key] = '';
                        }
                        if ($require[1] == 'int') {
                            $row[$data_key] = 0;
                        }
                        if ($require[1] == 'decimal') {
                            if ($require[2] == '2') {
                                $row[$data_key] = 0.00;
                            }
                            if ($require[2] == '3') {
                                $row[$data_key] = 0.000;
                            }
                        }
                    }
                }
                $row['type'] = '2';
                $row['cp_id'] = $cp_id ?? 0;
                $insertData[] = $row;
            }

            $chunk = 1000;
            $nums = ceil(count($insertData) / $chunk);
            $newInsertData = array_chunk($insertData, $chunk);

            for ($i = 0; $i < $nums; $i++) {
                \App\Store\Models\Member\SiteMemberConsumeRecord::query()->insert($newInsertData[$i]);


            }

            return response()->json(['code' => '000', 'msg' => '上传成功', 'data' => []]);
        } else {
            return response()->json(['code' => '001', 'msg' => '上传异常', 'data' => []]);
        }
    }

    /**
     *   导出筛选数据
     *
     */
    public function doexport(Request $request)
    {
        $head = [
            'mem_name' => '会员名',
            'mem_card_no' => '会员卡号',
            'mobile' => '手机号',
            'order_sn' => '订单号',
            'store_name' => '门店名称',
            'order_at' => '下单时间',
            'order_store' => '开单门店',
            'shopping_account'=>'导购',
            'goods_name' => '商品名称',
            'goods_sn_code' => '条码',
            'goods_category' => '商品类别',
            'cert_no' => '证书号',
            'goods_price' => '商品标价',
            'price' => '标价',
            'order_discount' => '折扣',
            'receive_money' => '应收金额',
            'recovery_money' => '回收金额',
            'points' => '积分',
            'piece_weight' => '件重',
            'glod_weight' => '金重',
            'sale_price' => '销售单价',
            'fee' => '工费',
            'real_money' => '实收金额',
            'goods_pricetype' => '价格类型',
            'count' => '数量',
            'discount_money' => '优惠金额',
            'cost_price' => '克销工费',
            'tag_price' => '牌价',
            'material_price' => '料价',
            'is_replace' => '是否已换',
            'remark' => '备注',
        ];
        $request->nowPage = 1;
        $request->limit = 5000;
        $request->columns = array_keys($head);

        $firstData = \App\Store\Models\Member\SiteMemberConsumeRecord::getlist($request)['list'];

        $nowPage = ceil($firstData['total'] / $request->limit);
        $nowPage = intval($nowPage);
        if ($nowPage > 40) {
            return response()->json(['code' => '001', 'msg' => '数据量过大请按筛选条件筛选后再导出', 'data' => []]);
        }
        $config = [
            'path' => $this->getTmpDir() . '/',
        ];
        $excel = new \Vtiful\Kernel\Excel($config);
        $filename = urlencode('其他消费记录导出_' . time() . '.xlsx');

        // Init File
        $excelObj = $excel->fileName($filename);

        $fileHandle = $excelObj->getHandle();
        $format = new \Vtiful\Kernel\Format($fileHandle);
        $backgroundStyle = $format->background(0x9bc2e6)->align(Format::FORMAT_ALIGN_CENTER, Format::FORMAT_ALIGN_VERTICAL_CENTER)->bold()->toResource();
        $excelObj = $excelObj->header(array_values($head), $backgroundStyle)->setRow('A1', 20);
        //去除特殊金额字段,其余统一 /100
        $keyAmount = ['receive_money', 'sale_price', 'fee', 'real_money', 'tag_price', 'material_price', 'cost_price', 'discount_money'];

        for ($i = 0; $i < $nowPage; $i++) {
            $request->nowPage = $i + 1;
            $list = \App\Store\Models\Member\SiteMemberConsumeRecord::getlist($request)['list'];
            if (!empty($list['data'])) {
                foreach ($list['data'] as $key => &$item) {
                    for ($ni = 0; $ni < count($keyAmount); $ni++) {
                        if (!empty($item[$keyAmount[$ni]])) {
                            $item[$keyAmount[$ni]] = $item[$keyAmount[$ni]] / 100;
                        }
                    }
                }
            }
            // Outptu
            $excelObj->data($list['data']);
        }

        $file = $excelObj->output();

        // Set Header
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Disposition: attachment;filename="' . $filename . '";filename*=utf-8');
//        header('Content-Length: ' . filesize($filePath));
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Cache-Control: max-age=0');
        header('Pragma: public');

        ob_clean();
        flush();

        if (copy($file, 'php://output') === false) {
            // Throw exception
        }

        // Delete temporary file
        @unlink($file);

    }

    public function getTmpDir(): string
    {
        $tmp = ini_get('upload_tmp_dir');

        if ($tmp !== False && file_exists($tmp)) {
            return realpath($tmp);
        }

        return realpath(sys_get_temp_dir());
    }

    public function dopostdel(Request $request)
    {
        $ids = $request->id;
        if (!isset($ids)) return response()->json(['code' => '001', 'msg' => 'id不能为空']);
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        $row = \App\Store\Models\Member\SiteMemberConsumeRecord::whereIn('id', $ids)->delete();
        if ($row > 0) {
            return response()->json(['code' => '000', 'msg' => '删除成功', 'data' => $row]);
        } else {
            return response()->json(['code' => '001', 'msg' => '删除失败', 'data' => $row]);
        }

    }

    //模板下载
    public function dodownloadtemplate(Request $request)
    {

        $head = [
            'mem_name' => '会员名',
            'mem_card_no' => '会员卡号',
            'mobile' => '手机号',
            'order_sn' => '订单号',
            'store_name' => '门店名称',
            'order_at' => '下单时间',
            'order_store' => '开单门店',
            'shopping_account' => '导购',
            'goods_name' => '商品名称',
            'goods_sn_code' => '条码',
            'goods_category' => '商品类别',
            'cert_no' => '证书号',
            'goods_price' => '商品标价',
            'price' => '标价',
            'order_discount' => '折扣',
            'receive_money' => '应收金额',
            'recovery_money' => '回收金额',
            'points' => '积分',
            'piece_weight' => '件重',
            'glod_weight' => '金重',
            'sale_price' => '销售单价',
            'fee' => '工费',
            'real_money' => '实收金额',
            'goods_pricetype' => '价格类型',
            'count' => '数量',
            'discount_money' => '优惠金额',
            'cost_price' => '克销工费',
            'tag_price' => '牌价',
            'material_price' => '料价',
            'is_replace' => '是否已换',
            'remark' => '备注',
        ];
        $row = [
            array_values($head)
        ];
        $options = [

        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
        ];
        $filename = '其他消费记录明细导入模板_' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);

    }
}
